博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Net实现阿里云开放云存储服务(OSS)
阅读量:6679 次
发布时间:2019-06-25

本文共 16608 字,大约阅读时间需要 55 分钟。

1 第一步框架搭建新建一个全新的MVC项目 (项目参考文档https://docs.aliyun.com/?spm=5176.383663.9.6.5OJI07#/pub/oss/sdk/sdk-download&dotnet)

2.第二步引用阿里成都程序集SDK 可以在NuGet搜索下载

 

3第三步代码实现

public class UploadFileHelper    {        public static OSSConfiguation _OssConfiguation;        public static OssClient ossClient;        public static string bucketName = "";        public static string accessid = ""; // AccessID        public static string accesskey = ""; // AccessKey        public static string endpoint = "";        public static string folder = "";        public static string localPath = "";        public static bool Islocal = false;        public static string imgBucket = "";        public static string pdfBucket = "";        static UploadFileHelper()        {            _OssConfiguation = (OSSConfiguation)System.Configuration.ConfigurationManager.GetSection("OSSConfig");            bucketName = _OssConfiguation.OssConfigService.imgBucket ==""                ? _OssConfiguation.OssConfigService.pdfBucket                : _OssConfiguation.OssConfigService.imgBucket;            accessid = _OssConfiguation.OssConfigService.accessid;            accesskey = _OssConfiguation.OssConfigService.accesskey;            endpoint = _OssConfiguation.OssConfigService.endpoint;            folder = _OssConfiguation.OssConfigService.folder;            localPath = _OssConfiguation.OssConfigService.localPath;            Islocal =Boolean.Parse(_OssConfiguation.OssConfigService.Islocal);        }        ///         /// 上传文件        ///         ///         /// 
public static bool UploadFile(HttpPostedFileBase file) { if (Islocal) { //本地存储Local return UploadLocalFile(file); } else { //开放存储OSS return UploadOSSFile(file); } } /// /// 上传本地文件 /// /// ///
private static bool UploadLocalFile(HttpPostedFileBase file) { try { string newfilename = file.FileName; string serverTempFilePath = localPath + newfilename; file.SaveAs(serverTempFilePath); return true; } catch (Exception) { return false; throw; } } /// /// 上传阿里云文件 /// /// ///
private static bool UploadOSSFile(HttpPostedFileBase file) { try { ossClient = new OssClient(endpoint, accessid, accesskey); //当然这里可以封装下 var meta = new ObjectMetadata(); meta.CacheControl = "max-age=315360000"; meta.ContentType = ContentType((file.FileName).Substring(file.FileName.LastIndexOf("."))); var stream = file.InputStream; string name = folder + "/" + file.FileName; PutObjectResult result = ossClient.PutObject(bucketName, name, stream, meta); var fileinfo = ossClient.GetObject(bucketName, name); AccessControlList accs = ossClient.GetBucketAcl(bucketName); string imgurl = string.Empty; if (!accs.Grants.Any()) //判断是否有读取权限 { imgurl = ossClient.GeneratePresignedUri(bucketName, name, DateTime.Now.AddMinutes(5)).AbsoluteUri; //生成一个签名的Uri 有效期5分钟 } else { imgurl = string.Format("http://{0}.oss.aliyuncs.com/{1}", bucketName, name); } return true; } catch (Exception ex) { return false; throw new Exception(ex.Message); } //Response.Write(string.Format("", imgurl)); } /// /// 类型 /// /// ///
public static string ContentType(String FilenameExtension) { string type = ""; if (FilenameExtension.Equals("BMP") || FilenameExtension.Equals("bmp")) { type = "image/bmp"; } if (FilenameExtension.Equals("GIF") || FilenameExtension.Equals("gif")) { type = "image/gif"; } if (FilenameExtension.Equals("JPEG") || FilenameExtension.Equals("jpeg") || FilenameExtension.Equals("JPG") || FilenameExtension.Equals("jpg") || FilenameExtension.Equals("PNG") || FilenameExtension.Equals("png")) { type = "image/jpeg"; } if (FilenameExtension.Equals("HTML") || FilenameExtension.Equals("html")) { type = "text/html"; } if (FilenameExtension.Equals("TXT") || FilenameExtension.Equals("txt")) { type = "text/plain"; } if (FilenameExtension.Equals("VSD") || FilenameExtension.Equals("vsd")) { type = "application/vnd.visio"; } if (FilenameExtension.Equals("PPTX") || FilenameExtension.Equals("pptx") || FilenameExtension.Equals("PPT") || FilenameExtension.Equals("ppt")) { type = "application/vnd.ms-powerpoint"; } if (FilenameExtension.Equals("DOCX") || FilenameExtension.Equals("docx") || FilenameExtension.Equals("DOC") || FilenameExtension.Equals("doc")) { type = "application/msword"; } if (FilenameExtension.Equals("XML") || FilenameExtension.Equals("xml")) { type = "text/xml"; } if (FilenameExtension.Equals("PFD") || FilenameExtension.Equals("pdf")) { type = "application/pdf"; } return type; } /// /// 创建模拟文件夹 /// public static void CreateFolderName() { // 初始化OssClient ossClient = new OssClient(endpoint, accessid, accesskey); const string key = "yourfolder/"; using (MemoryStream ms = new MemoryStream()) { ossClient.PutObject(bucketName, key, ms); } } /// /// 获取所有图片 /// public static OSSInfoListModel Bind() { var model = new OSSInfoListModel(); ossClient = new OssClient(accessid, accesskey); var buck = ossClient.ListBuckets(); var listing = ossClient.ListObjects(bucketName); model.Bucket = buck; model.ObjectListing = listing; return model; } /// /// 删除 /// /// /// ///
public static bool Delete(string bucketname, string key) { try { ossClient = new OssClient(accessid, accesskey); ossClient.DeleteObject(bucketname, key); return true; } catch (Exception) { return false; throw; } } /// /// 新建Bucket /// /// ///
public static bool CreateBucket(string bucketName) { try { // 初始化OssClient ossClient = new OssClient(endpoint, accessid, accesskey); // 新建一个Bucket ossClient.CreateBucket(bucketName); return true; } catch (Exception) { return false; throw; } } /// /// 获取所有的Bucket /// ///
public static IEnumerable
GetAllBucket() { // 初始化OssClient ossClient = new OssClient(endpoint, accessid, accesskey); var buckets = ossClient.ListBuckets(); return buckets; } ///
/// 判断Bucket是否存在 /// ///
///
public static bool GetBucketBybucketName(string name) { // 初始化OssClient ossClient = new OssClient(endpoint, accessid, accesskey); var exist = ossClient.ListBuckets().Any(b => b.Name.Equals(name)); return exist; } ///
/// 删除Bucket /// ///
public static bool DeleteBucket(string name) { try { // 初始化OssClient ossClient = new OssClient(endpoint, accessid, accesskey); ossClient.DeleteBucket(name); return true; } catch (Exception) { return false; throw; } } ///
/// 使用CNAME进行访问 /// public static void UseCName(HttpPostedFileBase file) { // 比如你的域名"http://my-cname.com"CNAME指向你的bucket域名"mybucket.oss-cn-hangzhou.aliyuncs.com" ossClient = new OssClient("http://my-cname.com/", accessid, accesskey); var meta = new ObjectMetadata(); meta.CacheControl = "max-age=315360000"; meta.ContentType = ContentType((file.FileName).Substring(file.FileName.LastIndexOf("."))); var stream = file.InputStream; string name = "test" + "/" + file.FileName; PutObjectResult result = ossClient.PutObject(bucketName, name, stream, meta); } ///
/// 创建文件夹 /// public static void CreateFolder() { // 初始化OssClient var client = new OssClient(endpoint, accessid, accesskey); // Note: key treats as a folder and must end with a slash. const string key = "yourfolder/"; // put object with zero bytes stream. using (MemoryStream ms = new MemoryStream()) { client.PutObject(bucketName, key, ms); } } }

 

为了更加易用我对一些基本参数进行了Web.Config的配置

代码实现如下:

public class OSSConfigHandler : IConfigurationSectionHandler    {        public object Create(object parent, object configContext, System.Xml.XmlNode section)        {            if (section == null)                throw new ArgumentNullException("section");            OSSConfiguation config;            if (parent != null)            {                var parentConfig = (OSSConfiguation) parent;                config = (OSSConfiguation) ((ICloneable) parentConfig).Clone();            }            else            {                config = new OSSConfiguation();            }            var services = new OSSConfigService();            for (int i = 0; i < section.ChildNodes.Count; i++)            {                try                {                    XmlNode element = section.ChildNodes.Item(i);                     if (element.NodeType == XmlNodeType.Comment) continue;                    if (element.Name == "OssConfigService")                    {                                               var bucketName = element.Attributes["bucketName"] != null ? element.Attributes["bucketName"].Value : "";                        var accessid = element.Attributes["accessid"] != null ? element.Attributes["accessid"].Value : "";                        var accesskey = element.Attributes["accesskey"] != null ? element.Attributes["accesskey"].Value : "";                        var endpoint = element.Attributes["endpoint"] != null ? element.Attributes["endpoint"].Value : "";                        var folder = element.Attributes["folder"] != null ? element.Attributes["folder"].Value : "";                        var Islocal = element.Attributes["Islocal"] != null ? element.Attributes["Islocal"].Value : "";                        var localPath = element.Attributes["localPath"] != null ? element.Attributes["localPath"].Value : "";                        var imgBucket = element.Attributes["imgBucket"] != null ? element.Attributes["imgBucket"].Value : "";                        var pdfBucket = element.Attributes["pdfBucket"] != null ? element.Attributes["pdfBucket"].Value : "";                        services.bucketName = bucketName;                        services.accessid = accessid;                        services.accesskey = accesskey;                        services.endpoint = endpoint;                        services.folder = folder;                        services.Islocal = Islocal;                        services.localPath = localPath;                        services.imgBucket = imgBucket;                        services.pdfBucket = pdfBucket;                    }                }                catch (Exception exception)                {                }            }            config.OssConfigService = services;            return config;        }    }
///     ///     ///     public class OSSConfigService    {        public OSSConfigService()        {        }        ///         ///         ///         public string bucketName { get; set; }        ///         ///         ///         public string accessid { get; set; }        ///         ///         ///         public string accesskey { get; set; }        ///         ///         ///         public string endpoint { get; set; }        ///         /// 文件夹        ///         public string folder { get; set; }        ///         ///         ///         public string  Islocal { get; set; }        ///         ///         ///         public string localPath { get; set; }        ///         ///         ///         public string imgBucket { get; set; }        ///         ///         ///         public string pdfBucket { get; set; }         }
public class OSSConfiguation : ICloneable    {        public OSSConfiguation()        {            OssConfigService = new OSSConfigService();        }        ///         ///         ///         public OSSConfigService OssConfigService { get; set; }        public object Clone()        {            throw new NotImplementedException();        }    }

Web.Config 的配置下 

 

 

Controller 调用

public class HomeController : Controller    {        public HomeController()        {        }        ///         ///         ///         /// 
public ActionResult Index() { var model= UploadFileHelper.Bind(); return View(model); } /// /// 上传 /// ///
public ActionResult FileSubmit() { var Picture = Request.Files[0]; var PDF = Request.Files[1]; bool s = false; var files = Request.Files; HttpPostedFileBase postedfile=null; for (int i = 0; i < files.Count; i++) { if (files[i].FileName.Length>0) { postedfile = files[i]; s = UploadFileHelper.UploadFile(postedfile); } } if (s) { return Content("上传成功"); } else { return Content("上传失败"); } } /// ///删除 /// /// /// ///
public void Delete(string key, string bucketname) { if(UploadFileHelper.Delete(bucketname, key)) { Response.Write("删除成功"); } else { Response.Write("删除失败"); } } /// /// 列表Bucket /// ///
public ActionResult ListBucket() { var buckets1 = UploadFileHelper.GetAllBucket(); return View(buckets1); } /// ///删除Bucket /// ///
public void DeleteBucket(string bucketname) { if (UploadFileHelper.DeleteBucket(bucketname)) { Response.Write("删除成功"); } else { Response.Write("删除失败"); } } /// /// /// ///
[HttpPost] public void CreateBucket() { string name = Request.Form["bucketname"]; if (UploadFileHelper.CreateBucket(name)) { Response.Write("创建成功"); } else { Response.Write("创建失败"); } } }

 

View:

@using (Html.BeginForm("FileSubmit", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))        {                                            }

此文为个人见解

转载于:https://www.cnblogs.com/ywsheng/p/4760987.html

你可能感兴趣的文章
新书问答:Software Wasteland
查看>>
Atlassian发布事故管理解决方案Jira Ops
查看>>
书评 —— 《Go语言编程》
查看>>
Apache HBase的现状和发展
查看>>
反模式的经典 - Mockito设计解析
查看>>
Zip Slip目录遍历漏洞已影响多个Java项目
查看>>
独家揭秘:微博深度学习平台如何支撑4亿用户愉快吃瓜?
查看>>
Visual Studio 15.7预览版4改进Git、C++支持
查看>>
全新云服务:亚马逊AWS发布AWS Ground Station\n
查看>>
微软宣布支持基于虚拟机的Azure IOT Edge服务
查看>>
来自社区的Visual Studio Code使用体验和教程
查看>>
高效运维最佳实践:如何做好On-call和事故响应?
查看>>
TypeScript 3.3发布:改进了联合类型调用和构建时间
查看>>
利用Scikit-Learn和Spark预测Airbnb的listing价格
查看>>
数据建模NoSQL数据库的概念和对象建模符号
查看>>
微软宣布Azure Function支持Python
查看>>
3·15曝光丨智能机器人一年拨打40亿个骚扰电话,6亿人信息已遭泄露!
查看>>
ArchSummit深圳2016大会7折售票最后一周
查看>>
2019年React学习路线图
查看>>
Google Docs API正式可用,可自动化文档任务和内容管理
查看>>